const router = require('koa-router')()
const { UserModel, UserInfoModel, MessageModel, MailListModel,departmentModel } = require('../db/pan')
const { StateModel } = require("../db/yan")
const { decrypt, encrypt } = require("../utils/methodsSet/index")
router.prefix('/pan')
const jwt = require("jsonwebtoken")

//测式接口
router.get('/', async function (ctx, next) {
  let data = await UserModel.find({})
  console.log(jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag'));
  ctx.body = {
    'name': '潘子庆',
    data
  }
})
router.get('/department',async function (ctx,next){
  let data=await departmentModel.find({})
  ctx.body={
    data
  }
})
//登录接口
router.post('/login', async function (ctx, next) {
  let body = ctx.request.body;
  let result = {}//响应对象
  let { username, password } = body//解构
  let validForm = await UserModel.find({ username })
  if (validForm.length == 0) { result['msg'] = '用户名不存在'; result['code'] = 404 }
  else {  
    let trueUser
    trueUser = validForm.find(item => { return decrypt(item.password) == password })//对密码进行解密并且验证密码
    if (trueUser == undefined) {
      result['msg'] = '请检查密码'; result['code'] = 404
    } else {
      result['token'] = jwt.sign({ "userid": trueUser.userinfo, "loginid": trueUser._id }, "flag", { expiresIn: (60 * 60)*2 })//过期时间为1小时
      result['msg'] = "登录成功了，hello ！！！"
      result['code'] = 200
    }
  }
  ctx.response.body = result
})
// 查找用户详细信息
router.get('/userinfo', async function (ctx, next) {
  let { userid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
  let result = {}
  if (userid == undefined) { result['msg'] = '请重新操作'; result['code'] = 404 }
  else {
    try {
      result['msg'] = '获取数据成功'
      result['code'] = 200
      result['data'] = await UserInfoModel.findOne({ _id: userid })
    } catch {
      result['msg'] = '你的关键参数格式有误'
      result['code'] = 404
    }
  }
  ctx.response.body = result
})
//注册功能
router.post('/reginster', async function (ctx, next) {
  let { username, password, mobile } = ctx.request.body;
  let result = {}
  // 先查询 数据库是否已有用户名
  let data = await UserModel.findOne({ username })
  let info = await UserInfoModel.findOne({ mobile })
  // 数据库 已有 重复 用户
  if (data !== null) { result['msg'] = '此用户名已经重复啦。'; result['code'] = 404 }
  else {
    if (info !== null) { result['msg'] = '此手机号已经绑定了。'; result['code'] = 404 }
    else {
      try {
        //可注册此用户
        let encryPwd = encrypt(password) //加密后的密码
        let reokinfo = await UserInfoModel.create({ mobile })
        await UserModel.create({ username, password: encryPwd, userinfo: reokinfo._id })
      } catch {
        result['msg'] = "注册失败，请重试。"; result['code'] = 404
      }
      result['msg'] = '注册成功了！！！'; result['code'] = 200
    }
  }
  ctx.response.body = result
})

// 修改密码
router.put('/repassword', async function (ctx, next) {
  let { password, newpassword, newpassword2 } = ctx.request.body;
  let result = {}
  let { userid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
  let user = await UserModel.findOne({ userinfo: userid })
  //校验要修改的密码和数据的密码是否一致
  if (password === newpassword) { result['code'] = 404; result['msg'] = '修改的密码和目前的密码一致，建议不修改' } else {
    try {
      if (newpassword === newpassword2) {//两次密码是否一致
        if (decrypt(user.password) === password) {//校验数据库的密码和 传来的密码是否一致
          await UserModel.updateOne({ userinfo: userid }, { password: encrypt(newpassword) })
          result['code'] = 200; result['msg'] = "修改成功，请重新登录。"
        } else {
          result['code'] = 404; result['msg'] = '请检查原密码'
        }
      } else {
        result['code'] = 404; result['msg'] = '您输入的两次密码不一致哦'
      }
    } catch {
      result['code'] = 404; result['msg'] = '操作失败，请重新操作'
    }
  }
  ctx.response.body = result
})
// 账号管理，修改邮箱、座机、手机，新注册的用户可能这里都是空的，需要手动修改。
router.put('/setMyinfo', async function (ctx, next) {
  let result = {}
  try {
    let { userid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
    let { email, telephone, mobile } = ctx.request.body;
    if (email !== undefined || telephone !== undefined || mobile !== undefined) {
      if (mobile == "") {
        result['code'] = 404; result['msg'] = '建议不要将手机号设为空';
      } else {
        let res = await UserInfoModel.updateOne({ _id: userid }, { email, telephone, mobile })
        result['code'] = 200; result['msg'] = '您的信息已经更新完成了。'
      }
    } else {
      result['code'] = 404; result['msg'] = '没有传入要修改的参数。'
    }
  }
  catch {
    result['code'] = 404; result['msg'] = '操作失败，请登录重试。'
  }
  ctx.response.body = result;
})


/**
 * type参数
 * all
 * me
 * either
 */
// 消息中心 列表
router.post('/msglist', async function (ctx, next) {
  let { type } = ctx.request.body;
  let result = {}
  try {
    if (type == 'all') {
      let res = await MessageModel.find().sort({ createTime: -1 }).populate("order")
      result['code'] = 200; result['msg'] = `获取全部消息成功`; result['data'] = res
    } else if (type == 'me') {
      let { userid, loginid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
      console.log(loginid);
      let data = await MessageModel.find().populate("order")
      console.log(data);
      let res = data.filter(item => {
        return item.order.processor_id.toString() === loginid.toString()//与我相关的"处理人"的订单
      })
      console.log(res || []);
      result['code'] = 200; result['msg'] = `获取与我相关的消息列表成功`; result['data'] = res
    }else if(type==='either'){
      result['code']=200;result['msg']='暂无相关数据';result['data']=[]
    }else{
      result['code'] = 404; result['msg'] = '参数值不对，或参数为空';
    }
  } catch {
    result['code'] = 404; result['msg'] = '操作失败，请重试。';
  }

  ctx.response.body = result
})

/**
 * type参数
 * all
 * me
 * either
 */
// 将消息的状态全部修改为已读
router.put('/allread', async function (ctx, next) {
  let { type } = ctx.request.body;
  let result = {}
  if (type === 'all') {
    let res = await MessageModel.updateMany({ state: 0 }, { state: 1 })
    result['code'] = 200; result['msg'] = `已经把${res.modifiedCount}条消息设为已读`;
  } else if (type == 'me') {
    let { userid, loginid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
    let data = await MessageModel.find().populate("order")
    let res = data.filter(item => {
      return item.order.processor_id.toString() === loginid.toString()//与我相关的"处理人"的订单
    })
    let num = 0;
    //跟我有关的消息都循环修改//
    for (let i = 0; i < res.length; i++) {
      let data2 = await MessageModel.updateOne({ _id: res[i]._id }, { state: 1 })
      num += data2.modifiedCount
    }
    result['code'] = 200; result['msg'] = `已经把${num}条消息设为已读`
  }
  ctx.response.body = result
})

//工单，消息通知，查看消息详情
router.post('/orderInfo', async function (ctx, next) {
  let { msgid } = ctx.request.body;
  let result = {}
  try {
    if (msgid !== undefined && msgid !== "") {
      let objs = await MessageModel.findOne({ _id: msgid })
      console.log(objs.order);
      let obj = await StateModel.findOne({ _id: objs.order.toString() }).populate('processor_id').populate('department').populate('repair_id')
      console.log(obj);
      let processor = await UserInfoModel.findOne({ _id: obj.processor_id.userinfo.toString() })
      let repair = await UserInfoModel.findOne({ _id: obj.repair_id.userinfo.toString() })
      let res = {
        _id: obj._id,
        types: obj.types,
        address: obj.address,
        // 联系人
        repair: repair.realname !== '' ? repair.realname : repair.nickname,
        repairMobile: repair.mobile,
        department: obj.department.dname,
        createTime: obj.create_time.getTime(),
        describe: obj.describe,
        old_imgs: obj.old_imgs,
        // 处理人
        processor: processor.realname !== '' ? processor.realname : processor.nickname,
        mobile: processor.mobile,
      }
      console.log(res);
      result['code'] = 200; result['msg'] = '查询消息详情成功'; result['data'] = res
    } else {
      result['code'] = 404; result['msg'] = '请携带必须参数'
    }
  }
  catch {
    result['code'] = 404; result['msg'] = '操作失败，请重试。'
  }
  ctx.response.body = result
})

//通讯录列表
router.get('/maillist',async function(ctx,next){
  let result = {}
  try{
    let { userid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
    let data = await MailListModel.find({ info:userid  })
    console.log(data);
    result['code']=200;result['msg']='获取通讯录成功';result['data']=data
  }catch{
    result['code'] = 404; result['msg'] = '操作失败，请重试。'
  }
  ctx.response.body = result
})
module.exports = router
